<template>
  <div>
    <!-- 场景1表单 -->
    <el-form>
      <!-- SPU名称 -->
      <el-form-item label="SPU名称">
        <el-input
          placeholder="请输入SPU名称"
          v-model="spuParams.spuName"
        ></el-input>
      </el-form-item>
      <!-- SPU品牌 -->
      <el-form-item label="SPU品牌">
        <el-select placeholder="请选择品牌" v-model="spuParams.tmId">
          <el-option
            :label="i.tmName"
            :value="i.id"
            v-for="i in trademarkName"
            :key="i.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- SPU描述 -->
      <el-form-item label="SPU描述">
        <el-input
          type="textarea"
          placeholder="请输入SPU描述"
          v-model="spuParams.description"
        ></el-input>
      </el-form-item>
      <!-- SPU图片 -->
      <el-form-item label="SPU图片">
        <!-- 替换图片上传地址 -->
        <el-upload
          v-model:file-list="imgAll"
          action="/app-dev/admin/product/upload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
        <!-- dialog解构 -->
        <el-dialog v-model="dialogVisible">
          <img
            style="
              width: 100px;
              height: 100px;
              margin: 10px auto;
              display: block;
            "
            :src="dialogImageUrl"
            alt="Preview Image"
          />
        </el-dialog>
      </el-form-item>
      <!-- 销售属性 -->
      <el-form-item label="销售属性">
        <el-select
          :placeholder="
            unSaleArrList.length > 0
              ? `您还有${unSaleArrList.length}项未选`
              : '无'
          "
          v-model="saleAttr"
        >
          <!-- select的v-model属性收集的是value属性值 -->
          <el-option
            :label="i.name"
            :value="`${i.id}:${i.name}`"
            v-for="i in unSaleArrList"
            :key="i.id"
          ></el-option>
        </el-select>
        <!-- 添加销售属性按钮 -->
        <el-button
          type="primary"
          :icon="Plus"
          style="margin: 0 10px"
          @click="addSaleAttr"
          :disabled="saleAttr ? false : true"
          >添加销售属性</el-button
        >
        <!-- table -->
        <el-table style="margin: 10px 0" border :data="saleArrList">
          <el-table-column
            label="序号"
            align="center"
            type="index"
            width="80"
          ></el-table-column>

          <el-table-column
            label="属性名"
            width="100"
            prop="saleAttrName"
          ></el-table-column>

          <el-table-column label="属性值">
            <template #="{ row, $index }">
              <el-tag
                v-for="(i, index) in row.spuSaleAttrValueList"
                @close="row.spuSaleAttrValueList.splice(index, 1)"
                :key="i.id"
                closable
                :type="i.id % 2 === 0 ? 'success' : 'warning'"
                style="margin: 5px"
              >
                {{ i.saleAttrValueName }}
              </el-tag>
              <!-- 按钮 -->
              <el-button
                v-if="!row.show"
                size="small"
                @click="toEdit(row)"
                :icon="Plus"
                type="primary"
              ></el-button>
              <!-- input -->
              <el-input
                v-else
                style="width: 100px; dispaly: inline-block"
                v-model="row.str"
                ref="formVC"
                @blur="toLook(row)"
                size="small"
                placeholder="请输入属性值"
              ></el-input>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="100">
            <template #="{ row, $index }">
              <el-button
                :icon="Delete"
                size="small"
                type="danger"
                @click="clear($index)"
              />
            </template>
          </el-table-column>
        </el-table>
        <!-- 底部按钮 -->
        <el-button type="primary" @click="submitParams" :disabled="saleArrList.length > 0 ?false :true">保存</el-button>
        <el-button @click="showZero">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted } from "vue";

import { ref, reactive, nextTick } from "vue";
import { Plus, Delete } from "@element-plus/icons-vue";
import type { UploadProps, UploadUserFile } from "element-plus";
import { ElMessage } from "element-plus";
//请求
import {
  reqAddOrUpdateSpu,
  reqTrademarkName,
  reqImgList,
  reqsaleArrList,
  reqallSaleAttrList,
} from "@/api/product/spu/index";

//删除按钮的回调
let clear = ($index: number) => {
  saleArrList.value.splice($index, 1);
};

//提交按钮的回调
let submitParams = async () => {
  //准备参数
  // 准备img对象,
  let spuImageList = imgAll.value.map((item: any) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url,
    };
  });
  spuParams.spuImageList = spuImageList;

  spuParams.spuSaleAttrList = saleArrList.value;

  //发请求
  try {
    await reqAddOrUpdateSpu(spuParams);
    // 弹框
    ElMessage({
      message: spuParams.id ? "修改成功" : "添加成功",
      type: "success",
    });
    //跳转回0
    $emit("changeShowOne", {newScene: 0 ,falg:spuParams.id?'update':''});
  } catch (e) {
    // 弹框
    ElMessage({
      message: spuParams.id ? "修改失败" : "添加失败",
      type: "error",
    });
  }
};
// 切换input
let toEdit = (row: any) => {
  row.show = true;
  row.str = "";
  nextTick(() => {
    // 鼠标聚焦
    formVC.value.focus();
  });
};
// 切换按钮
let toLook = (row: any) => {
  // 准备参数
  let saleAttrValueObj = {
    saleAttrValueName: row.str,
    baseSaleAttrId: row.baseSaleAttrId,
  };

  //非法情况判断:属性值的名字不能为空
  if (saleAttrValueObj.saleAttrValueName.trim() == "") {
    ElMessage({
      message: "属性值不能为空",
      type: "error",
    });
    //属性值为空后面语句不在执行

    return;
  }

  //非法情况:新增的属性值是否在数组当中出现
  let repeat = row.spuSaleAttrValueList.find((item: any) => {
    return saleAttrValueObj.saleAttrValueName === item.saleAttrValueName;
  });

  if (repeat) {
    ElMessage({
      message: "属性值不能重复",
      type: "error",
    });
    return;
  }

  //全部判断正确插入数据
  row.spuSaleAttrValueList.push(saleAttrValueObj);
  // 切换读模式
  row.show = false;
};
//imputVC实例
let formVC = ref();
//添加销售属性按钮的回调
let addSaleAttr = () => {
  if (!saleAttr.value) return;
  //分解销售属性
  let [baseSaleAttrId, saleAttrName] = saleAttr.value.split(":");
  //添加到表格渲染数组里
  saleArrList.value.push({
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  });
  //清空数据
  saleAttr.value = "";
};
//定义销售属性的拼接字符串
let saleAttr = ref("");
//存储全部品牌名称
let trademarkName = ref([]);
//存储已有图片列表
let imgAll = ref([]);
//存储已有销售属性
let saleArrList = ref([]);
//存储全部销售属性
let allSaleArrList = ref([]);
//计算未选择销售属性
let unSaleArrList = computed((): any => {
  let arr = allSaleArrList.value.filter((item: any) => {
    return saleArrList.value.every((item1: any) => {
      return item1.saleAttrName != item.name;
    });
  });
  return arr;
});
//请求数据
let spuParams = reactive({
  category3Id: "",
  description: "",
  spuImageList: [],
  spuName: "",
  spuSaleAttrList: [],
  tmId: "",
});
//添加spu按钮的回调(父组件调用)
let addSpu = async (c3id: string | number) => {
  // 覆盖原有内容
  Object.assign(spuParams, {
    // 传入c3id用于发请求
    category3Id: c3id,
    description: "",
    spuImageList: [],
    spuName: "",
    spuSaleAttrList: [],
    tmId: "",
  });
  //获取全部品牌
  let result:any = await reqTrademarkName();
  //获取全部销售属性
  let result1:any = await reqallSaleAttrList();

  //存储数据
  trademarkName.value = result
  allSaleArrList.value = result1
  // 清空数据
  imgAll.value = []
  saleArrList.value = []
  // 删除id
  delete spuParams.id
};

// 上传图片用到的内容 --------------
// 图片格式 name:xxx  url:xxx
const dialogImageUrl = ref("");
// diglog状态切换
const dialogVisible = ref(false);
// 图片中的删除按钮
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  //uploadFile:图片信息
  // uploadFiles:剩余图片的对象
};
// 点击图片的回调mmda
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  // 将图片地址暂存,在dialog中显示
  dialogImageUrl.value = uploadFile.url!;
  // 显示dialog
  dialogVisible.value = true;
};

// 自定义事件接收
let $emit = defineEmits(["changeShowOne"]);
// 取消按钮的回调,切换场景0
let showZero = () => {
  $emit("changeShowOne", {newScene:0,falg:'update'});
};

// 发请求封装函数
let getData = async (row: any) => {
  // 替换信息
  Object.assign(spuParams, row);
  // 获取商品牌
  let result: any = await reqTrademarkName();
  //获取图片列表
  let result1: any = await reqImgList(row.id);
  // 获取已有销售属性
  let result2: any = await reqsaleArrList(row.id);
  //获取全部销售属性
  let result3: any = await reqallSaleAttrList();
  //存储数据
  trademarkName.value = result;
  // 将img图片数组内的的属性名修改为可用的属性名
  imgAll.value = result1.map((item: any) => {
    // 请求回来的数据属性名与upload图片上传的属性名不一致,需要进行加工
    return {
      name: item.imgName,
      url: item.imgUrl,
    };
  });
  saleArrList.value = result2;
  allSaleArrList.value = result3;
};

// 对外暴露组件方法
defineExpose({ getData, addSpu });
</script>

<style scoped>
</style>